﻿using System;
using System.Collections.Generic;
using System.Text;

namespace UtilZ.Dotnet.Ex.Model
{
    /// <summary>
    /// 选中项类型
    /// </summary>
    /// <typeparam name="T">源类型</typeparam>
    public class CheckItem<T> : CheckItemBase where T : ICheckItemShow
    {
        private readonly T _source;
        /// <summary>
        /// 数据源
        /// </summary>
        public T Source
        {
            get { return _source; }
        }

        /// <summary>
        /// 显示名称
        /// </summary>
        public override string Text
        {
            get
            {
                if (this._source == null)
                {
                    return null;
                }

                return this._source.Text;
            }
            set
            {
                if (this._source == null)
                {
                    throw new NotSupportedException();
                }

                this._source.Text = value;
            }
        }






        /// <summary>
        /// 选中项改变前处理回调
        /// </summary>

        private readonly Action<CheckedArgs<T>> _checkedChanged;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="source">数据源</param>
        public CheckItem(T source)
            : base()
        {
            this._source = source;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="isChecked">是否选中[true:选中;false:未选中]</param>
        /// <param name="checkedChanged">选中项改变前处理回调</param>
        public CheckItem(T source, bool isChecked, Action<CheckedArgs<T>> checkedChanged = null)
            : base(isChecked)
        {
            this._source = source;
            this._checkedChanged = checkedChanged;
        }


        /// <summary>
        /// 选中项改变前处理
        /// 返回值:是否更新选中状态[true:更新;false:不更新]
        /// </summary>
        /// <param name="oldChecked">旧的的选中状态</param>
        /// <param name="newChecked">新的的选中状态</param>
        /// <returns>是否更新选中状态[true:更新;false:不更新]</returns>
        protected override bool OnPreCheckedChanged(bool oldChecked, bool newChecked)
        {
            if (this._checkedChanged == null)
            {
                return true;
            }

            var args = new CheckedArgs<T>(this._source, oldChecked, newChecked);
            this._checkedChanged(args);
            return args.UpdateChecked;
        }
    }
}
